//
//  CustomDatePickerView.swift
//  YOKO
//
//  Created by vivi on 6/5/16.
//  Copyright © 2016 15Tec. All rights reserved.
//

import UIKit
import SnapKit

class CustomDatePickerView: UIView {
    
    var yearMonthDayDatePicker = YearMonthDayDatePickerView()
    var hourMinuteDatePicker = HourMinuteDatePickerView()
    
    var minimumDate: NSDate = NSDate.MinDate {
        didSet {
            checkDate(false)
        }
    }
    var maximumDate: NSDate = NSDate.MaxDate {
        didSet {
            checkDate(false)
        }
    }
    
    var date: NSDate {
        get {
            let dayDate = NSDate(year: yearMonthDayDatePicker.year, month: yearMonthDayDatePicker.month, day: yearMonthDayDatePicker.day)
            let hour_24 = (hourMinuteDatePicker.hour_12 + (hourMinuteDatePicker.amOrPm == .PM ? 12 : 0)) % 24
            let secondsSince = NSTimeInterval(hour_24 * 3600 + hourMinuteDatePicker.minute * 60)
            let minuteDate = NSDate(timeInterval: secondsSince, sinceDate: dayDate)
            return minuteDate
        }
        set {
            setDate(newValue, animated: false)
        }
    }
    
    var datePickerMode: UIDatePickerMode = .Date {
        didSet {
            if datePickerMode == .Time { hourMinuteDatePicker.hidden = false }
            else { hourMinuteDatePicker.hidden = true }
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        configureInit()
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        configureInit()
    }
    
    func configureInit() {
        self.addSubview(yearMonthDayDatePicker)
        self.addSubview(hourMinuteDatePicker)
        
        yearMonthDayDatePicker.snp_makeConstraints { make in make.edges.equalTo(self)}
        hourMinuteDatePicker.snp_makeConstraints { make in make.edges.equalTo(self) }
        
        setDate(NSDate(), animated: false)
    }
    
    func setDate(date: NSDate, animated: Bool) {
        yearMonthDayDatePicker.setYearTo(date.year, animated: animated)
        yearMonthDayDatePicker.setMonthTo(date.month, animated: animated)
        yearMonthDayDatePicker.setDayTo(date.day, animated: animated)
        hourMinuteDatePicker.setHour12(date.hour % 12, animated: animated)
        hourMinuteDatePicker.setMinute(date.minute, animated: animated)
        hourMinuteDatePicker.setAmPm(date.hour > 12 ? .PM : .AM, animated: animated)        
    }
    
    func checkDate(animated: Bool) {
        if self.date < self.minimumDate {
            setDate(self.minimumDate, animated: animated)
        }
        else if self.date > self.maximumDate {
            setDate(self.maximumDate, animated: animated)
        }
    }
}
